package com.dyys.extension.extra.view;

import com.dyys.extension.extra.Extra;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.impl.BeanAsArraySerializer;
import com.fasterxml.jackson.databind.ser.impl.ObjectIdWriter;
import com.fasterxml.jackson.databind.ser.std.BeanSerializerBase;

import java.io.IOException;
import java.util.Map;
import java.util.Set;

public class ExtraBeanSerializer extends BeanSerializerBase {
	private static final long serialVersionUID = 1L;

	public ExtraBeanSerializer(BeanSerializerBase source) {
        super(source);
    }

    public ExtraBeanSerializer(ExtraBeanSerializer source, 
            ObjectIdWriter objectIdWriter) {
        super(source, objectIdWriter);
    }
    
    public ExtraBeanSerializer(ExtraBeanSerializer source, 
    		ObjectIdWriter objectIdWriter, Object filterId) {
    	super(source, objectIdWriter, filterId);
    }

    public ExtraBeanSerializer(ExtraBeanSerializer source, 
    		Set<String> toIgnore) {
        super(source, toIgnore);
    }

    public BeanSerializerBase withObjectIdWriter(ObjectIdWriter objectIdWriter) {
        return new ExtraBeanSerializer(this, objectIdWriter);
    }

	@Override
	protected BeanSerializerBase withIgnorals(Set<String> toIgnore) {
		return new ExtraBeanSerializer(this, toIgnore);
	}

    public void serialize(Object bean, JsonGenerator jgen,
            SerializerProvider provider) throws IOException,
            JsonGenerationException {           
        jgen.writeStartObject();                        
        serializeFields(bean, jgen, provider);

        if (Extra.class.isAssignableFrom(bean.getClass())){
            Map<String, Object> ext = ((Extra)bean).getExt();
            if (ext!=null) {
                for (Map.Entry<String, Object> kv : ext.entrySet()) {
                    jgen.writeObjectField(kv.getKey(), kv.getValue());
                }
            }
        }
        jgen.writeEndObject();
    }

	@Override
	protected BeanSerializerBase asArraySerializer() {
        /* Cannot:
         * 
         * - have Object Id (may be allowed in future)
         * - have "any getter"
         * - have per-property filters
         */
        if ((_objectIdWriter == null)
                && (_anyGetterWriter == null)
                && (_propertyFilterId == null)
                ) {
            return new BeanAsArraySerializer(this);
        }
        // already is one, so:
        return this;
	}

	@Override
	public BeanSerializerBase withFilterId(Object filterId) {
		return new ExtraBeanSerializer(this, _objectIdWriter, filterId);
	}

}
